﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Common.Library;
using OnlineVideos.Data;
using System.Xml.Linq;
using OnlineVideos.Entities;
using OnlineVideos.Common;
using System.Windows.Media.Imaging;


namespace OnlineVideos.ViewModels
{
    public class History
    {
        private int GetMaxHistoryID(ref XDocument doc)
        {
            int ID = 1;
            var DescendingHistoryList = from i in doc.Descendants("h")
                                        orderby Convert.ToInt32(i.Attribute("id").Value) descending
                                        select i;

            if (DescendingHistoryList != null)
            {
                if (DescendingHistoryList.ElementAt(0) != null)
                    ID = Convert.ToInt32(DescendingHistoryList.ElementAt(0).Attribute("id").Value);
                ID++;
            }
            return ID;
        }

        private void SaveHistoryRootItem(string file, string itemID, string itemName)
        {
            XDocument xdoc = new XDocument(new XElement("mh",
                                new XElement("h",
                                    new XAttribute("id", 1),
                                    new XAttribute("mid", itemID),
                                    new XAttribute("cno", itemName))));
            Storage.SaveFileFromDocument(file, xdoc);
        }

        private void SaveHistoryItem(string file, string itemID, string itemName)
        {
            if (Storage.FileExists(file))
            {
                XDocument xdoc = Storage.ReadFileAsDocument(file);
                if (xdoc.Document != null)
                {
                    int ID = GetMaxHistoryID(ref xdoc);

                    var eles = from f in xdoc.Descendants("h") select f;

                    int MaxHistoryNo = 30;

                    if (eles.Count() >= MaxHistoryNo)
                    {
                        int HistoryIdToRemove = ID - MaxHistoryNo;
                        (from r in xdoc.Descendants("h") where r.Attribute("id").Value == HistoryIdToRemove.ToString() select r).Remove();
                    }

                    XElement xele = new XElement("h",
                            new XAttribute("id", ID),
                            new XAttribute("mid", itemID),
                            new XAttribute("cno", itemName));
                    xdoc.Root.Add(xele);
                    Storage.SaveFileFromDocument(file, xdoc);
                }
                else
                    SaveHistoryRootItem(file, itemID, itemName);
            }
            else
                SaveHistoryRootItem(file, itemID, itemName);
        }

        public void SaveMovieHistory(string movieID, string chapterNo)
        {
            SaveHistoryItem(Constants.MovieHistoryFile, movieID, chapterNo);
        }

        public void SaveSongHistory(string songID, string songName)
        {
            SaveHistoryItem(Constants.SongHistoryFile, songID, songName);
        }
        public void SaveAudioHistory(string songID, string songName)
        {
            SaveHistoryItem(Constants.AudioHistoryFile, songID, songName);
        }
        public List<LinkHistory> LoadMovieHistory(int FirstIndex, int LastIndex, int Count)
        {
            return GetHistoryList(Constants.MovieHistoryFile, FirstIndex, LastIndex, Count, LinkType.Movies);
        }

        public List<LinkHistory> LoadSongHistory(int FirstIndex, int LastIndex, int Count)
        {
            return GetHistoryList(Constants.SongHistoryFile, FirstIndex, LastIndex, Count, LinkType.Songs);
        }
        public List<LinkHistory> LoadAudioHistory(int FirstIndex, int LastIndex, int Count)
        {
            return GetHistoryList(Constants.AudioHistoryFile, FirstIndex, LastIndex, Count, LinkType.Audio);
        }
        public List<LinkHistory> 
            GetHistoryList(string file, int StartIndex, int LastIndex, int Count, LinkType linkType)
        {
            List<LinkHistory> LinkHistoryList = new List<LinkHistory>();
            try
            {
                if (Storage.FileExists(file))
                {
                    XDocument xdoc = Storage.ReadFileAsDocument(file);

                    var HistoryList = from f in xdoc.Descendants("h")
                                      where (Convert.ToInt32(f.Attribute("id").Value) >= StartIndex && Convert.ToInt32(f.Attribute("id").Value) <= LastIndex)
                                      select f;

                    foreach (var history in HistoryList)
                    {
                        long showID = Convert.ToInt32(history.Attribute("mid").Value);
                        string songname = history.Attribute("cno").Value;
                        ShowLinks LinkInfo = OnlineShow.GetLinkDetailByTitle(linkType, Convert.ToInt32(history.Attribute("mid").Value), 
                                                                        history.Attribute("cno").Value);
                        ShowList showInfo = OnlineShow.GetShowDetailForHistory(showID);

                        LinkHistory objHistory = new LinkHistory();
                        objHistory.ShowID = showID;
                        objHistory.ID = history.Attribute("id").Value;
                        if(LinkInfo!=null)
                        objHistory.LinkUrl = LinkInfo.LinkUrl;
                        objHistory.SubTitle = showInfo.SubTitle;
                        if (ResourceHelper.AppName == "webslice")
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            objHistory.ImgSource = Storage.ReadBitmapImageFromFile("/" + ResourceHelper.ProjectName + Constants.ImagePath + showInfo.TileImage,BitmapCreateOptions.None);
                        });

                        }
                        else if (ResourceHelper.AppName == "Video_Mix")
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                objHistory.ImgSource = Storage.ReadBitmapImageFromFile("/" + ResourceHelper.ProjectName + Constants.ImagePath + showInfo.TileImage, BitmapCreateOptions.None);
                                objHistory.SubTitle =null;
                            });
                        }
                        else
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                BitmapImage bimage = new BitmapImage();
                                bimage.UriSource = new Uri(Constants.ImagePath + showInfo.TileImage, UriKind.Relative);
                                objHistory.ImgSource = bimage;
                            });

                        }
                        objHistory.Title = showInfo.Title;
                     
                        objHistory.Genre = showInfo.Genre;
                       objHistory.ReleaseDate = showInfo.ReleaseDate;
                        objHistory.ImageRating = ImageHelper.LoadRatingImage(showInfo.Rating.ToString()).ToString();

                        if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                            objHistory.LinkTitle = history.Attribute("cno").Value;
                        else
                            objHistory.LinkTitle = showInfo.Title + " - " + history.Attribute("cno").Value;

                        if (AppSettings.SongID == objHistory.ID.ToString() && AppSettings.AudioImage == Constants.PlayImagePath)
                            objHistory.Songplay = Constants.SongPlayPath;
                        else
                            objHistory.Songplay = Constants.PlayImagePath;

                        LinkHistoryList.Add(objHistory);
                    }
                }

                if (LinkHistoryList.Count == Count && StartIndex != 1)
                    LinkHistoryList.Add(new LinkHistory() { LinkTitle = "get more" });
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in GetHistoryList Method In History.cs file", ex);
            }
            return LinkHistoryList;
        }

        public int GetLastHisId(string file)
        {
            int Id = 0;
            try
            {
                XDocument xdoc = Storage.ReadFileAsDocument(file);
                if(xdoc != null)
                    Id = GetMaxHistoryID(ref xdoc) - 1;
            }
            catch (Exception ex)
            {
                ex.Data.Add("file", file);
                Exceptions.SaveOrSendExceptions("Exception in GetLastHisId Method In History.cs file", ex);
            }
            return Id;
        }
    }
}
